package cn.jzk.mySpringSecurity_noSeparation.SecurityHandler;

import cn.jzk.mySpringSecurity_noSeparation.Common.Enums.AppHttpCodeEnum;
import cn.jzk.mySpringSecurity_noSeparation.Common.Exception.MyException;
import cn.jzk.mySpringSecurity_noSeparation.Common.Result.ResponseResult;
import cn.jzk.mySpringSecurity_noSeparation.Common.Utils.MyJsonUtils;
import cn.jzk.mySpringSecurity_noSeparation.Entity.LoginUser;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import java.io.IOException;
import java.io.PrintWriter;

/**
 * 登录用户【认证成功】响应处理器
 * @author jiangzk
 */
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                                        Authentication authentication) throws IOException{

        // 1.获取当前认证成功的用户信息，比对返回的类型
        Object principal = authentication.getPrincipal();
        if (!(principal instanceof LoginUser)) {
            throw new MyException(HttpStatus.BAD_REQUEST.value(),
                    "登陆认证成功后，authentication.getPrincipal()返回的Object对象必须是：LoginUser！");
        }

        // 2.设置响应的内容类型和字符集
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setCharacterEncoding("UTF-8");

        // 3.返回自定义的 JSON 响应信息
        try (PrintWriter writer = response.getWriter()) {
            writer.print(MyJsonUtils.stringify(
                    ResponseResult.okResult(AppHttpCodeEnum.SUCCESS.getCode(), "登录成功")));
        }
    }
}
